package db.ibatis;

import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.util.Properties;

/**
 * Created by boot on 12/1/15.
 */

@Intercepts(value = {
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})

})

public class TimerInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(TimerInterceptor.class);

    private String p;

    public Object intercept(Invocation invocation) throws Throwable {
        System.out.println("==========> " + this.p);
        Object target = invocation.getTarget();
        Object result = null;
        if (target instanceof Executor) {
            long start = System.currentTimeMillis();
            Method method = invocation.getMethod();
            // 执行方法

            result = invocation.proceed();
            long end = System.currentTimeMillis();
            logger.info(String.format("[TimerInterceptor] execute [%s] cost [%s] ms", method.getName(), end - start));
        }
        return result;
    }


    public Object plugin(Object target) {
        System.out.println("plugin method is running...");
        return Plugin.wrap(target, this);
    }


    public void setProperties(Properties properties) {
        System.out.println("setting properties now ...");
        this.p = properties.getProperty("p1");
    }
}
